<template>
  <view class="seg-action-container">
    <!-- 此部分懒得封装了，直接些业务代码算了   -->
    <view v-if="(device === 'desktop' && type === 'desktop') ||
                (uniLeftMenuState.matchLeftWindow === true && type === 'desktop')">
      <uni-table border stripe style="overflow:visible;">
        <uni-tr>
          <uni-td align="left">
            <view class="action-item">
              <u--text type="info" :text="selectMenu.selectUName.name" class="item-select-left"></u--text>
              <u--input v-model="userInfo.userName" :disabled="true"></u--input>
            </view>
          </uni-td>
          <uni-td align="left">
            <view class="action-item">
              <u--text type="info" :text="selectMenu.selectPName.name" class="item-select-left"></u--text>
              <u--input v-model="pName" :disabled="true"></u--input>
            </view>
          </uni-td>
          <uni-td align="left">
            <view>
              <u-button
                  type="primary" :text="getTranslate(0)"
                  @click="startPredict" :loading="buttonStatus.process_loading"
                  :disabled="buttonStatus.process_button"
              ></u-button>
            </view>
          </uni-td>
        </uni-tr>
        <uni-tr>
          <uni-td align="left">
            <view class="action-item">
              <u--text type="info" :text="selectMenu.selectEnhance.name" class="item-select-left">></u--text>
              <uni-data-select :localdata="selectMenu.selectEnhance.data" v-model="formSheet.selectChoice.enhance_choice"></uni-data-select>
            </view>
          </uni-td>
          <uni-td align="left">
            <view class="action-item">
              <u--text type="info" :text="selectMenu.selectSeg.name" class="item-select-left"></u--text>
              <uni-data-select :localdata="selectMenu.selectSeg.data" v-model="formSheet.selectChoice.segmentation_choice"></uni-data-select>
            </view>
          </uni-td>
          <uni-td align="left">
            <view>
              <u-button
                  type="primary" :text="getTranslate(1)"
                  @click="startDownload" :disabled="buttonStatus.download_button"></u-button>
            </view>
          </uni-td>
        </uni-tr>
        <uni-tr>
          <uni-td align="left">
            <view class="action-item">
              <u--text type="info" :text="selectMenu.selectGrade.name" class="item-select-left"></u--text>
              <uni-data-select :localdata="selectMenu.selectGrade.data" v-model="formSheet.selectChoice.grade_choice"></uni-data-select>
            </view>
          </uni-td>
          <uni-td align="left">
            <view class="action-item">
              <u--text type="info" :text="selectMenu.selectVascular.name" class="item-select-left"></u--text>
              <uni-data-select :localdata="selectMenu.selectVascular.data" v-model="formSheet.selectChoice.vascular_choice"></uni-data-select>
            </view>
          </uni-td>
          <uni-td align="left">
            <view>
              <u-button
                  type="primary" :text="getTranslate(2)"
                  @click="startExcelExport" :disabled="buttonStatus.export_button"></u-button>
            </view>
          </uni-td>
        </uni-tr>
      </uni-table>
    </view>
    <view v-else>
      <u--form labelPosition="left" ref="form1" :model="formSheet" labelWidth="120">
        <u-form-item :label="selectMenu.selectUName.name" borderBottom>
          <u--input v-model="userInfo.userName" :disabled="true"></u--input>
        </u-form-item>
        <u-form-item :label="selectMenu.selectPName.name" borderBottom>
          <u--input v-model="pName" :disabled="true"></u--input>
        </u-form-item>
        <u-form-item :label="selectMenu.selectEnhance.name" borderBottom>
          <uni-data-select :localdata="selectMenu.selectEnhance.data" v-model="formSheet.selectChoice.enhance_choice"></uni-data-select>
        </u-form-item>
        <u-form-item :label="selectMenu.selectSeg.name" borderBottom>
          <uni-data-select :localdata="selectMenu.selectSeg.data" v-model="formSheet.selectChoice.segmentation_choice"></uni-data-select>
        </u-form-item>
        <u-form-item :label="selectMenu.selectGrade.name" borderBottom>
          <uni-data-select :localdata="selectMenu.selectGrade.data" v-model="formSheet.selectChoice.grade_choice"></uni-data-select>
        </u-form-item>
        <u-form-item :label="selectMenu.selectVascular.name" borderBottom>
          <uni-data-select :localdata="selectMenu.selectVascular.data" v-model="formSheet.selectChoice.vascular_choice"></uni-data-select>
        </u-form-item>
        <u-form-item>
          <u-row justify="space-between" style="width: 100%" gutter="10">
            <u-col span="6">
              <u-button
                  type="primary" :text="getTranslate(0)"
                  @click="startPredict" :disabled="buttonStatus.process_button"
                  :loading="buttonStatus.process_loading"
              ></u-button>
            </u-col>
            <u-col span="6">
              <u-button
                  type="primary" :text="getTranslate(1)"
                  @click="startDownloadWithMobile"
                  :disabled="buttonStatus.download_button"
              ></u-button>
            </u-col>
            <!--            <u-col span="4"><u-button type="primary" text="数据导出""></u-button></u-col>-->
          </u-row>
        </u-form-item>
      </u--form>
    </view>
  </view>
</template>

<script>
import calCommon from "../../utils/winCal/calCommon";
import UniFormsItem from "../uni-forms-item/uni-forms-item";
import UniTable from "../uni-table/uni-table";
import UniDataSelect from '../uni-data-select/uni-data-select'
import appConfig from "../../api/appConfig";
import {mapState} from "vuex";
import flaskApi from "../../api/flaskApi";
import language from "../../api/language";
import flaskService from "../../api/modules/flaskService";

export default {
  name: "segServiceActionSelect",
  components: {UniTable, UniFormsItem, UniDataSelect},
  mixins: [calCommon],
  computed: {
    ...mapState('user', ['userInfo']),
    ...mapState('app', ['nowLanguage']),
    ...mapState('componentCommunicate', ['clickUpload', 'clickEachHistory']),
    selectMenu(){
      let lang = this.nowLanguage
      if (lang === "CHI") return appConfig.selectMenu
      else return appConfig.selectMenuEng
    }
  },
  watch: {
    clickUpload(newVal, oldVal){
      this.changeButtonStatus(0)
    },
    clickEachHistory(newVal, oldVal){
      if(this.nowPredict === -1){
        this.changeButtonStatus(2)
      }
    }
    // uNameToken(newVal, oldVal){
    //   console.log('token已经改变', newVal)
    // }
  },
  props: {
    uNameEncode: {
      default: '',  // 这个可以自行读取vuex的内容
      type: String
    },
    uNameToken: {
      default: '',  // 这个需要获取图片上传的序列
      type: String
    },
    pName: {
      default: '',
      type: String
    },
    type: {
      default: 'desktop',  // 用于强制覆盖行为
      type: String
    }
  },
  mounted() {
    this.tableCal()
    this.imgCal()

    this.changeButtonStatus(0)
  },
  data() {
    return {
      buttonStatus: {
        // 点击开始处理，进入loading动画，等待完成的回调
        process_button: false,
        process_loading: false,
        download_button: true,
        export_button: true
      },
      formSheet: {
        selectChoice: {
          enhance_choice: 0,
          segmentation_choice: 0,
          grade_choice: 0,
          vascular_choice: 0
        }
      },
      redisKey: '',  // 返回的redis id
      exportData: {
        // 抛出的内容
        progress: 0,  // 25: enhance, 50: segmentation, 75: grade, 100: vascular
        description: '',  // 具体的文件
        title: '',  // 进行到什么阶段了
        type: ''  // 消息类型
      },
      intervalObj: Object,
      waitingIntervalObj: Object,
      nowPredict: -1  // 当前是否在进行预测
    }
  },
  methods: {
    changeButtonStatus(state){
      if(state === 0) {
        // 最开始的状态，禁用下载，导出
        this.buttonStatus = {
          process_button: false,
          process_loading: false,
          download_button: true,
          export_button: true
        }
      }else if(state === 1){
        // 运算中
        this.buttonStatus = {
          process_button: true,
          process_loading: true,
          download_button: true,
          export_button: true
        }
      }else if(state === 2){
        // 可以下载
        this.buttonStatus = {
          process_button: false,
          process_loading: false,
          download_button: false,
          export_button: false
        }
      }
    },
    getTranslate(posIndex){
      let langDict = language.getTranslate(language.segServiceActionSelect)
      if (posIndex === 0){
        return langDict.startProcess
      }else if(posIndex === 1){
        return langDict.download
      }else if(posIndex === 2){
        return langDict.dataOutput
      }else if(posIndex === 3){
        return langDict.redisError
      }else if(posIndex === 4){
        return langDict.waiting1
      }else if(posIndex === 5){
        return langDict.waiting2
      }
    },
    change(e){
      console.log(this.formSheet.selectChoice)
    },

    startWaiting(){
      // 等待队列的显示
      let that = this

      const fail = (res) => {
        uni.showModal({
          title: 'error',
          content: JSON.stringify(res),
          showCancel: false
        })
        that.changeButtonStatus(0)
        this.nowPredict = -1
      }

      const success = (res) => {

        if(res.data.result){
          if(res.data.message === 0){
            clearInterval(this.waitingIntervalObj)
            that.startInterval()
          }else{
            that.exportData.title = that.getTranslate(4)
            that.exportData.type = 'primary'
            that.exportData.description = that.getTranslate(5) + res.data.message
            that.exportData.progress = -1
            that.$emit("LongTaskStatusChange", that.exportData)
          }
        }else{
          fail(res)
        }
      }

      this.waitingIntervalObj = setInterval(()=>{
        flaskService.flaskQueueQuery(that.redisKey, success, fail)
      }, 1200)
    },

    startPredict(){
      this.nowPredict = 0
      this.changeButtonStatus(1)
      let that = this

      const fail = (res) => {
        uni.showModal({
          title: 'error',
          content: JSON.stringify(res),
          showCancel: false
        })
        that.changeButtonStatus(0)
        this.nowPredict = -1
      }

      const success = (res) => {
        if(res.data.result){
          that.redisKey = res.data.id
          that.startWaiting()
        }else{
          uni.showModal({
            title: "tips",
            content: res.data.message,
            showCancel: false
          })
          that.changeButtonStatus(0)
          this.nowPredict = -1
        }
      }
      flaskService.flaskPredictV1(this.uNameEncode, this.uNameToken, this.formSheet.selectChoice, success, fail)

    },

    startDownloadWithMobile(){
      let d1 = flaskApi.DOWNLOAD_EXCEL + "?user_name=" + this.uNameEncode + "&token=" + this.uNameToken + "&img_list=" + "['*']"
      let d2 = flaskApi.DOWNLOAD_ZIP + "?user_name=" + this.uNameEncode + "&token=" + this.uNameToken + "&language=" + "CHI"

      const downloadFunction = (url)=>{
        const iframe = document.createElement('iframe')
        iframe.style.display = 'none'
        iframe.style.height = 0
        iframe.src = url
        document.body.appendChild(iframe)
        setTimeout(()=>{
          iframe.remove()
        }, 5 * 60 * 1000)
      }

      downloadFunction(d1)
      downloadFunction(d2)
    },
    startDownload(){
      let lang = this.nowLanguage
      if (lang === '') lang = 'CHI'
      let downloadUrl = flaskApi.DOWNLOAD_ZIP + "?user_name=" + this.uNameEncode + "&token=" + this.uNameToken + "&language=" + lang
      const a = document.createElement('a')
      a.href = downloadUrl
      a.download = downloadUrl
      a.style.display = 'none'
      a.target = "_blank"

      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)

    },
    startExcelExport(){
      let lang = this.nowLanguage
      if (lang === '') lang = 'CHI'
      let downloadUrl = flaskApi.DOWNLOAD_EXCEL + "?user_name=" + this.uNameEncode + "&token=" + this.uNameToken + "&img_list=" + "['*']" + "&language=" + lang
      const a = document.createElement('a')
      a.href = downloadUrl
      a.download = downloadUrl
      a.style.display = 'none'
      a.target = "_blank"

      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    },
    startInterval(){
      let that = this
      if(this.redisKey === ''){
        uni.showModal({
          title: "tips",
          content: that.getTranslate(3),
          showCancel: false
        })
        this.changeButtonStatus(0)
        this.nowPredict = -1
      }else{
        this.intervalObj = setInterval(()=>{
          let that = this
          let formData = {
            redis_id: this.redisKey
          }
          uni.request({
            url: flaskApi.LONG_TASK_MONITOR,
            method: "POST",
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            data: formData,
            success: (res) => {
              // debugger
              let message = res.data.message
              try{
                that.exportData.description = message.file_name.toString()
              }catch (e){
                return ;
              }

              // that.exportData.title = message.state
              that.exportData.title = message.state.replace('vascular', 'Quantification')
              that.exportData.type = 'success'
              if (message.has_finished === true){
                that.exportData.progress = 100
                that.stopInterval()
              }else{
                let state = message.state
                // 25: enhance, 50: segmentation, 75: grade, 100: vascular
                if (state.indexOf('enhance') !== -1){
                  that.exportData.progress = 25
                }else if(state.indexOf('segmentation') !== -1){
                  that.exportData.progress = 50
                }else if(state.indexOf('grade') !== -1){
                  that.exportData.progress = 75
                }else{
                  that.exportData.progress = 95
                }
              }
              that.$emit("LongTaskStatusChange", that.exportData)
            },
            fail: (res) => {
              // debugger
              that.exportData.title = 'error'
              that.exportData.description = JSON.stringify(res)
              that.exportData.type = 'error'
              that.$emit("LongTaskStatusChange", that.exportData)
              that.changeButtonStatus(0)
              this.nowPredict = -1
            }
          })
        }, 1000)
      }
    },
    stopInterval(){
      this.nowPredict = -1
      this.changeButtonStatus(2)
      clearInterval(this.intervalObj)
    }
  }
}
</script>

<style scoped>
.seg-action-container{
  margin: 20px 0;
  overflow:visible;
}
.action-item {
  display: flex;
}
.item-select-left {
  flex: 0 0 40%
}
.item-select-right {
  flex: 0 0 60%
}
</style>
